package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.ProductVo;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author zgh
 * @date 2024-11-12
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(100);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        //调用第三方查询产品列表
        QueryProductListResponse response;
        try{
            response = client.queryProductList(request);
        }catch(Exception e){
            throw new BaseException("物联网接口 查询产品,同步失败");
        }

        //判断 如果数据为空,则中断请求
        if(!response.getBody().success){
            throw new BaseException("物联网接口 查询产品,调用失败");
        }

        //存储到redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String string = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        if (StringUtils.isEmpty(string)){
            // 如果数据为空，则返回一个空集合
            return Collections.emptyList();
        }
        //解析数据并返回
        return JSONUtil.toList(string, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        // 判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        long count = count(queryWrapper);
        if (count > 0){
            throw new BaseException("设备名称已存在,请重新输入");
        }
        // 保存设备到iot平台
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try{
            response = client.registerDevice(registerDeviceRequest);
        }catch (Exception e){
            throw new BaseException("物联网接口 注册设备,调用失败");
        }
        // 判断保存设备到iot平台是否成功
        if (!response.getBody().success){
            throw new RuntimeException(response.getBody().getErrorMessage());
        }
        // 查询产品数据
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        QueryProductResponse productResponse;
        try {
            productResponse = client.queryProduct(queryProductRequest);
        }catch (Exception e){
            throw new BaseException("物联网接口 查询产品,调用失败");
        }
        // 判断接口是否调通
        if(!productResponse.getBody().success){
            throw new BaseException("物联网接口 查询产品,调用失败");
        }
        // 设置产品名称到设备对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setProductName(productResponse.getBody().getData().getProductName());

        //物理位置
        if (device.getLocationType().equals(0)){
            device.setPhysicalLocationType(-1);
        }
        // 补全设备id
        device.setIotId(response.getBody().getData().getIotId());
        try{
            deviceMapper.insertDevice(device);
        }catch (Exception e){
            // 删除iot中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setDeviceName(deviceDto.getDeviceName());
            deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
            deleteDeviceRequest.setIotId(device.getIotId());
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            try{
                client.deleteDevice(deleteDeviceRequest);
            }catch (Exception ex){
                throw new BaseException("物联网接口 删除设备,调用失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }

    }
}
